package com.java1412.config;

import com.alibaba.druid.pool.xa.DruidXADataSource;
import com.atomikos.jdbc.AtomikosDataSourceBean;
import org.springframework.boot.autoconfigure.orm.jpa.JpaProperties;
import org.springframework.boot.orm.jpa.EntityManagerFactoryBuilder;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Primary;
import org.springframework.data.jpa.repository.config.EnableJpaRepositories;
import org.springframework.orm.jpa.JpaTransactionManager;
import org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean;
import org.springframework.transaction.PlatformTransactionManager;

import javax.annotation.Resource;
import javax.sql.DataSource;
import java.util.Objects;

/**
 * @author java1412
 * @create 2021-07-07 16:26
 */
@Configuration
@EnableJpaRepositories(basePackages = {"com.java1412.dao.db1"},
        entityManagerFactoryRef = "goodsEntityManagerFactory",
        transactionManagerRef = "goodsTransactionManager")
public class GoodsDataSourceConfig {
    @Resource
    private JpaProperties jpaProperties;
    /**
     * 第一个数据源
     *
     * @return
     */
    @Primary
    @Bean(name = "goodsDataSource")
    public DataSource goodsDataSource() {
        DruidXADataSource druidXADataSource = new DruidXADataSource();
        druidXADataSource.setUrl("jdbc:mysql://localhost:3306/db1?characterEncoding=utf-8&useSSL=false&serverTimezone=UTC");
        druidXADataSource.setUsername("root");
        druidXADataSource.setPassword("ok");
        druidXADataSource.setDefaultAutoCommit(false);
        AtomikosDataSourceBean atomikosDataSourceBean = new AtomikosDataSourceBean();
        atomikosDataSourceBean.setXaDataSource(druidXADataSource);
        atomikosDataSourceBean.setUniqueResourceName("goodsDataSource");
        atomikosDataSourceBean.setPoolSize(5);
        return atomikosDataSourceBean;
    }

    /**
     * 商品实体类管理工厂
     *
     * @param builder
     * @return
     */
    @Primary
    @Bean(name = "goodsEntityManagerFactory")
    public LocalContainerEntityManagerFactoryBean goodsEntityManagerFactory(EntityManagerFactoryBuilder builder) {
        return builder.dataSource(goodsDataSource())
                .properties(jpaProperties.getProperties())
                // 设置实体类所在位置：类或包
                .packages("com.java1412.entity.db1")
                // 持久化单元名称
                .persistenceUnit("goodsPersistenceUnit").build();
    }

    @Primary
    @Bean(name = "goodsTransactionManager")
    public PlatformTransactionManager goodsTransactionManager(EntityManagerFactoryBuilder builder) {
        return new JpaTransactionManager(Objects.requireNonNull(goodsEntityManagerFactory(builder).getObject()));
    }
}
